document.addEventListener('DOMContentLoaded', function() {
    // 点赞功能
    const likeButtons = document.querySelectorAll('.like-btn');
    likeButtons.forEach(button => {
        button.addEventListener('click', async function() {
            if (!isAuthenticated) {
                window.location.href = loginUrl;
                return;
            }
            const coupleId = this.dataset.coupleId;
            try {
                const response = await fetch(`/couple/${coupleId}/like`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                const data = await response.json();
                if (data.success) {
                    const likeCount = this.querySelector('.like-count');
                    likeCount.textContent = data.likes_count;
                    this.classList.add('liked');
                }
            } catch (error) {
                console.error('Error:', error);
            }
        });
    });

    // 评论表单处理
    const commentForm = document.getElementById('comment-form');
    if (commentForm) {
        commentForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            if (!isAuthenticated) {
                window.location.href = loginUrl;
                return;
            }
            
            const commentInput = document.getElementById('comment-input');
            const content = commentInput.value.trim();
            if (!content) {
                toast.show('评论内容不能为空', 'error');
                return;
            }

            try {
                const response = await fetch(`/comment/${coupleId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ content })
                });

                if (!response.ok) {
                    throw new Error('评论提交失败');
                }

                const data = await response.json();
                if (data.id) {
                    addNewComment(data);
                    commentInput.value = '';
                    toast.show('评论发表成功', 'success');
                }
            } catch (error) {
                console.error('Error:', error);
                toast.show('评论提交失败，请稍后重试', 'error');
            }
        });
    }

    // 投票功能
    const voteButtons = document.querySelectorAll('.vote-btn');
    voteButtons.forEach(button => {
        button.addEventListener('click', async function() {
            if (!isAuthenticated) {
                window.location.href = loginUrl;
                return;
            }

            const voteType = this.dataset.vote;
            try {
                const response = await fetch(`/couple/${coupleId}/vote`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ vote_type: voteType })
                });
                
                if (!response.ok) {
                    const data = await response.json();
                    toast.show(data.error || '投票失败', 'error');
                    return;
                }

                const data = await response.json();
                if (data.success) {
                    // 更新投票计数和进度条
                    document.querySelector('.stay-count').textContent = data.vote_counts.stay_together;
                    document.querySelector('.divorce-count').textContent = data.vote_counts.divorce;
                    
                    // 计算并更新进度条宽度
                    const totalVotes = data.vote_counts.stay_together + data.vote_counts.divorce;
                    const stayWidth = totalVotes > 0 ? (data.vote_counts.stay_together / totalVotes * 100) : 0;
                    const divorceWidth = totalVotes > 0 ? (data.vote_counts.divorce / totalVotes * 100) : 0;

                    //更新并获得票数
                    document.querySelector('.progress.stay .progress-text').textContent = "继续走下去 " + data.vote_counts.stay_together + "票";
                    document.querySelector('.progress.divorce .progress-text').textContent = "和平分手 " + data.vote_counts.divorce + "票";

                    
                    document.querySelector('.progress.stay .progress-bar').style.width = `${stayWidth}%`;
                    document.querySelector('.progress.divorce .progress-bar').style.width = `${divorceWidth}%`;
                    
                    // 更新按钮状态
                    if (data.vote_cancelled) {
                        // 取消投票状态
                        this.classList.remove('voted');
                        toast.show('已取消投票', 'info');
                    } else {
                        // 更新所有按钮状态
                        voteButtons.forEach(btn => {
                            btn.classList.remove('voted');
                        });
                        // 设置当前按钮为已投票状态
                        this.classList.add('voted');
                        toast.show('投票成功', 'success');
                    }
                }
            } catch (error) {
                console.error('Error:', error);
                toast.show('投票失败，请稍后重试', 'error');
            }
        });
    });

    // 评论点赞功能
    document.querySelectorAll('.like-comment').forEach(btn => {
        btn.addEventListener('click', async function() {
            if (!isAuthenticated) {
                window.location.href = loginUrl;
                return;
            }
            
            const commentId = this.dataset.commentId;
            const isLiked = this.classList.contains('liked');
            const endpoint = `/comment/${commentId}/${isLiked ? 'unlike' : 'like'}`;
            
            try {
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                if (!response.ok) {
                    const data = await response.json();
                    toast.show(data.error || '操作失败', 'error');
                    return;
                }
                
                const data = await response.json();
                if (data.success) {
                    const likeCount = this.querySelector('.like-count');
                    likeCount.textContent = data.likes_count;
                    this.classList.toggle('liked');
                    toast.show(isLiked ? '已取消点赞' : '点赞成功', 'success');
                }
            } catch (error) {
                console.error('Error:', error);
                toast.show('操作失败，请稍后重试', 'error');
            }
        });
    });

    // 名言轮播
    const quotes = document.querySelectorAll('.quote-card');
    let currentQuote = 0;
    
    function showNextQuote() {
        quotes[currentQuote].classList.remove('active');
        currentQuote = (currentQuote + 1) % quotes.length;
        quotes[currentQuote].classList.add('active');
    }

    if (quotes.length > 1) {
        setInterval(showNextQuote, 5000);
    }

    // 回复按钮点击处理
    document.querySelectorAll('.reply-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const commentId = this.dataset.commentId;
            const replyForm = document.getElementById(`reply-form-${commentId}`);
            
            // 关闭其他打开的回复表单
            document.querySelectorAll('.reply-form').forEach(form => {
                if (form !== replyForm && form.style.display === 'block') {
                    form.style.display = 'none';
                }
            });
            
            replyForm.style.display = replyForm.style.display === 'none' ? 'block' : 'none';
            if (replyForm.style.display === 'block') {
                replyForm.querySelector('.reply-input').focus();
            }
        });
    });

    // 取消回复按钮处理
    document.querySelectorAll('.cancel-reply').forEach(btn => {
        btn.addEventListener('click', function() {
            const replyForm = this.closest('.reply-form');
            replyForm.style.display = 'none';
            replyForm.querySelector('.reply-input').value = '';
        });
    });

    // 提交回复处理
    document.querySelectorAll('.submit-reply').forEach(btn => {
        btn.addEventListener('click', async function() {
            const commentId = this.dataset.commentId;
            const replyForm = document.getElementById(`reply-form-${commentId}`);
            const replyInput = replyForm.querySelector('.reply-input');
            const content = replyInput.value.trim();
            
            if (!content) {
                toast.show('回复内容不能为空', 'error');
                return;
            }

            try {
                const response = await fetch(`/comment/${commentId}/reply`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ content })
                });
                
                if (!response.ok) {
                    throw new Error('回复提交失败');
                }

                const data = await response.json();
                if (data.id) {
                    // 添加新回复到页面
                    const repliesContainer = this.closest('.comment').querySelector('.replies') || 
                        createRepliesContainer(this.closest('.comment'));
                    const replyElement = createReplyElement(data);
                    repliesContainer.appendChild(replyElement);
                    
                    // 清空输入框并隐藏回复表单
                    replyInput.value = '';
                    replyForm.style.display = 'none';
                    
                    toast.show('回复成功', 'success');
                }
            } catch (error) {
                console.error('Error:', error);
                toast.show('回复提交失败，请稍后重试', 'error');
            }
        });
    });

    // 展开更多回复按钮处理
    document.querySelectorAll('.show-more-replies').forEach(btn => {
        btn.addEventListener('click', function() {
            const commentId = this.dataset.commentId;
            const hiddenReplies = this.nextElementSibling;
            
            if (hiddenReplies.style.display === 'none') {
                hiddenReplies.style.display = 'block';
                this.textContent = '收起回复';
            } else {
                hiddenReplies.style.display = 'none';
                const totalReplies = parseInt(this.dataset.totalReplies);
                this.textContent = `展开更多回复 (${totalReplies - 3})`;
            }
        });
    });

    // 为新添加的回复绑定事件
    function createReplyElement(reply) {
        const div = document.createElement('div');
        div.className = 'comment card reply';
        
        // 格式化时间
        const timestamp = new Date(reply.timestamp);
        const formattedTime = new Intl.DateTimeFormat('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        }).format(timestamp);
        
        div.innerHTML = `
            <div class="comment-header">
                <span class="comment-author">${reply.author}</span>
                <span class="comment-time">${formattedTime}</span>
            </div>
            <div class="comment-content">
                ${reply.content}
            </div>
            <div class="comment-actions">
                <button class="btn btn-sm like-comment" data-comment-id="${reply.id}">
                    <i class="fas fa-thumbs-up"></i>
                    <span class="like-count">0</span>
                </button>
            </div>
        `;
        
        // 绑定事件
        bindReplyEvents(div);
        
        return div;
    }
});

// 辅助函数
function addNewComment(comment) {
    const commentsList = document.querySelector('.comments-list');
    const commentElement = document.createElement('div');
    commentElement.className = 'comment card';
    
    // 格式化时间
    const timestamp = new Date(comment.timestamp);
    const formattedTime = new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
    }).format(timestamp);
    
    commentElement.innerHTML = `
        <div class="comment-header">
            <span class="comment-author">${comment.author}</span>
            <span class="comment-time">${formattedTime}</span>
        </div>
        <div class="comment-content">
            ${comment.content}
        </div>
        <div class="comment-actions">
            <button class="btn btn-sm like-comment" data-comment-id="${comment.id}">
                <i class="fas fa-thumbs-up"></i>
                <span class="like-count">0</span>
            </button>
            <button class="btn btn-sm reply-btn" data-comment-id="${comment.id}">
                <i class="fas fa-reply"></i> 回复
            </button>
        </div>
        <div class="reply-form" id="reply-form-${comment.id}" style="display: none;">
            <textarea class="form-control reply-input" placeholder="写下你的回复..."></textarea>
            <div class="reply-actions">
                <button class="btn btn-sm submit-reply" data-comment-id="${comment.id}">发送回复</button>
                <button class="btn btn-sm cancel-reply">取消</button>
            </div>
        </div>
        <div class="replies"></div>
    `;
    commentsList.insertBefore(commentElement, commentsList.firstChild);

    // 为新添加的评论绑定事件监听器
    const likeBtn = commentElement.querySelector('.like-comment');
    const replyBtn = commentElement.querySelector('.reply-btn');
    const submitReplyBtn = commentElement.querySelector('.submit-reply');
    const cancelReplyBtn = commentElement.querySelector('.cancel-reply');

    // 点赞事件
    likeBtn.addEventListener('click', async function() {
        if (!isAuthenticated) {
            window.location.href = loginUrl;
            return;
        }
        
        const commentId = this.dataset.commentId;
        const isLiked = this.classList.contains('liked');
        const endpoint = `/comment/${commentId}/${isLiked ? 'unlike' : 'like'}`;
        
        try {
            const response = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
            
            if (!response.ok) {
                const data = await response.json();
                toast.show(data.error || '操作失败', 'error');
                return;
            }
            
            const data = await response.json();
            if (data.success) {
                const likeCount = this.querySelector('.like-count');
                likeCount.textContent = data.likes_count;
                this.classList.toggle('liked');
                toast.show(isLiked ? '已取消点赞' : '点赞成功', 'success');
            }
        } catch (error) {
            console.error('Error:', error);
            toast.show('操作失败，请稍后重试', 'error');
        }
    });

    // 回复按钮事件
    replyBtn.addEventListener('click', function() {
        const replyForm = document.getElementById(`reply-form-${comment.id}`);
        
        // 关闭其他打开的回复表单
        document.querySelectorAll('.reply-form').forEach(form => {
            if (form !== replyForm && form.style.display === 'block') {
                form.style.display = 'none';
            }
        });
        
        replyForm.style.display = replyForm.style.display === 'none' ? 'block' : 'none';
        if (replyForm.style.display === 'block') {
            replyForm.querySelector('.reply-input').focus();
        }
    });

    // 提交回复事件
    submitReplyBtn.addEventListener('click', async function() {
        const replyForm = document.getElementById(`reply-form-${comment.id}`);
        const replyInput = replyForm.querySelector('.reply-input');
        const content = replyInput.value.trim();
        
        if (!content) {
            toast.show('回复内容不能为空', 'error');
            return;
        }

        try {
            const response = await fetch(`/comment/${comment.id}/reply`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ content })
            });
            
            if (!response.ok) {
                throw new Error('回复提交失败');
            }

            const data = await response.json();
            if (data.id) {
                // 添加新回复到页面
                const repliesContainer = commentElement.querySelector('.replies');
                const replyElement = createReplyElement(data);
                repliesContainer.appendChild(replyElement);
                
                replyInput.value = '';
                replyForm.style.display = 'none';
                
                toast.show('回复成功', 'success');
            }
        } catch (error) {
            console.error('Error:', error);
            toast.show('回复提交失败，请稍后重试', 'error');
        }
    });

    // 取消回复事件
    cancelReplyBtn.addEventListener('click', function() {
        const replyForm = this.closest('.reply-form');
        replyForm.style.display = 'none';
        replyForm.querySelector('.reply-input').value = '';
    });
}

function updateVoteUI(voteCounts) {
    const stayCount = document.querySelector('.stay-count');
    const divorceCount = document.querySelector('.divorce-count');
    if (stayCount && divorceCount) {
        stayCount.textContent = voteCounts.stay_together;
        divorceCount.textContent = voteCounts.divorce;
    }
}

// 创建回复元素的辅助函数
function createReplyElement(reply) {
    const div = document.createElement('div');
    div.className = 'comment card reply';
    
    // 格式化时间
    const timestamp = new Date(reply.timestamp);
    const formattedTime = new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
    }).format(timestamp);
    
    div.innerHTML = `
        <div class="comment-header">
            <span class="comment-author">${reply.author}</span>
            <span class="comment-time">${formattedTime}</span>
        </div>
        <div class="comment-content">
            ${reply.content}
        </div>
        <div class="comment-actions">
            <button class="btn btn-sm like-comment" data-comment-id="${reply.id}">
                <i class="fas fa-thumbs-up"></i>
                <span class="like-count">0</span>
            </button>
        </div>
    `;
    
    // 绑定事件
    bindReplyEvents(div);
    
    return div;
}

function handleCommentSubmit(e) {
    e.preventDefault();
    const content = commentInput.value.trim();
    if (!content) {
        showMessage('评论内容不能为空', 'error');
        return;
    }

    const coupleId = window.location.pathname.split('/').pop();
    submitComment(content, coupleId);
}

async function submitComment(content, coupleId) {
    try {
        const response = await fetch(`/comment/${coupleId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ content })
        });

        if (!response.ok) {
            throw new Error('评论提交失败');
        }

        const data = await response.json();
        addNewComment(data);
        commentInput.value = '';
        showMessage('评论发表成功', 'success');
    } catch (error) {
        console.error('Error:', error);
        showMessage('评论提交失败，请稍后重试', 'error');
    }
}

// 添加消息提示函数
function showMessage(message, type = 'info') {
    // 检查是否已存在 toast 容器
    let container = document.querySelector('.toast-container');
    if (!container) {
        container = document.createElement('div');
        container.className = 'toast-container';
        document.body.appendChild(container);
    }

    // 创建新的 toast
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;

    // 添加到容器
    container.appendChild(toast);

    // 设置消失动画
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateY(-20px)';
        toast.style.transition = 'all 0.3s ease-out';
        
        // 移除元素
        setTimeout(() => {
            toast.remove();
            // 如果没有更多 toast，移除容器
            if (container.children.length === 0) {
                container.remove();
            }
        }, 300);
    }, 2000);
}

// 创建回复容器
function createRepliesContainer(commentElement) {
    const repliesDiv = document.createElement('div');
    repliesDiv.className = 'replies';
    commentElement.appendChild(repliesDiv);
    return repliesDiv;
}

// 绑定点赞事件
function bindLikeEvent(button) {
    button.addEventListener('click', async function() {
        // ... 点赞事件处理代码 ...
    });
}

// 绑定回复按钮事件
function bindReplyEvent(button) {
    button.addEventListener('click', function() {
        // ... 回复按钮事件处理代码 ...
    });
}

// 绑定提交回复事件
function bindSubmitReplyEvent(button) {
    button.addEventListener('click', async function() {
        // ... 提交回复事件处理代码 ...
    });
}

// 将bindReplyEvents函数移到DOMContentLoaded事件监听器外部
function bindReplyEvents(element) {
    // 点赞按钮
    const likeBtn = element.querySelector('.like-comment');
    if (likeBtn) {
        likeBtn.addEventListener('click', async function() {
            if (!isAuthenticated) {
                window.location.href = loginUrl;
                return;
            }
            
            const commentId = this.dataset.commentId;
            const isLiked = this.classList.contains('liked');
            const endpoint = `/comment/${commentId}/${isLiked ? 'unlike' : 'like'}`;
            
            try {
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                if (!response.ok) {
                    const data = await response.json();
                    toast.show(data.error || '操作失败', 'error');
                    return;
                }
                
                const data = await response.json();
                if (data.success) {
                    const likeCount = this.querySelector('.like-count');
                    likeCount.textContent = data.likes_count;
                    this.classList.toggle('liked');
                    toast.show(isLiked ? '已取消点赞' : '点赞成功', 'success');
                }
            } catch (error) {
                console.error('Error:', error);
                toast.show('操作失败，请稍后重试', 'error');
            }
        });
    }

    // 回复按钮
    const replyBtn = element.querySelector('.reply-btn');
    if (replyBtn) {
        replyBtn.addEventListener('click', function() {
            const replyForm = document.getElementById(`reply-form-${this.dataset.commentId}`);
            if (replyForm) {
                replyForm.style.display = replyForm.style.display === 'none' ? 'block' : 'none';
                if (replyForm.style.display === 'block') {
                    replyForm.querySelector('.reply-input').focus();
                }
            }
        });
    }
} 